package com.guyaogg.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guyaogg.common.to.es.SkuEsModel;
import com.guyaogg.common.utils.R;
import com.guyaogg.gulimall.search.config.GulimallElasticSearchConfig;
import com.guyaogg.gulimall.search.constant.EsConstant;
import com.guyaogg.gulimall.search.feign.ProductFeignService;
import com.guyaogg.gulimall.search.service.MallSearchService;
import com.guyaogg.gulimall.search.vo.AttrResponseVO;
import com.guyaogg.gulimall.search.vo.BrandVO;
import com.guyaogg.gulimall.search.vo.SearchParam;
import com.guyaogg.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 顾遥
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    private static final String HTTP_SEARCH_LIST = "http://search.gulimall.com/list.html?";
    private final RestHighLevelClient client;
    private final ProductFeignService productFeignService;

    private final String splitChar = "_";

    public MallSearchServiceImpl(RestHighLevelClient client, ProductFeignService productFeignService) {
        this.client = client;
        this.productFeignService = productFeignService;
    }

    @Override
    public SearchResult search(SearchParam param) {
        // 动态构建出 dsl 语句
        SearchResult result = null;

        // 1.准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            // 2.执行检索请求
            SearchResponse searchResponse = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            log.debug("es 响应数据：{}", searchResponse);
            // 3.分析响应数据，封装成想要的数据
            result = assignSearchResponse(searchResponse, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param response 响应数据
     * @return 分析响应数据，构建结果数据
     */
    private SearchResult assignSearchResponse(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();

        SearchHits hits = response.getHits();
//        // 所有查询到的商品
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 关键词高亮
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highlightSkuTitle = skuTitle.fragments()[0].string();
                    esModel.setSkuTitle(highlightSkuTitle);
                }
                esModels.add(esModel);
            }
        }

        result.setProducts(esModels);
//
//        // 当前所有商品涉及到的所有属性信息
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVO> attrs = attrIdAgg.getBuckets().stream().map(bucket -> {
            // 属性 id
            long attrId = bucket.getKeyAsNumber().longValue();
            // 属性名字
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            // 属性值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValue = attrValueAgg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            return new SearchResult.AttrVO(attrId, attrName, attrValue);
        }).collect(Collectors.toList());

        result.setAttrs(attrs);
//
//        // 品牌信息
        List<SearchResult.BrandVO> brands = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            // 品牌 id
            long brandId = bucket.getKeyAsNumber().longValue();
            // 品牌名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            // 品牌图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brands.add(new SearchResult.BrandVO(brandId, brandName, brandImg));
        }

        result.setBrands(brands);
//
//        // 分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        List<SearchResult.CatalogVO> catalogs = buckets.stream().map(bucket -> {
            // 分类 id
            SearchResult.CatalogVO catalog = new SearchResult.CatalogVO();
            catalog.setCatalogId(bucket.getKeyAsNumber().longValue());
            // 分类名字
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalog.setCatalogName(catalogName);
            return catalog;
        }).collect(Collectors.toList());

        result.setCatalogs(catalogs);

//        =============== 以上是从聚合信息中获取================
//
//        // 页码信息
        result.setPageNum(param.getPageNum());
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        int pages = (int) ((total - 1) / EsConstant.PRODUCT_PAGE_SIZE + 1);
        result.setTotalPages(pages);
        List<Integer> pageNovs = new ArrayList<>();
        int begin = param.getPageNum() - 2;
        for (int i = begin, c = 0; c < 5; i++, c++) {
            i = begin + c;
            if (i >= 1 && i <= pages) {
                pageNovs.add(i);

            }
        }
        result.setPageNavs(pageNovs);

        if (param.getAttrs() != null && !param.getAttrs().isEmpty()) {
            // 追加面包屑导航功能
            List<SearchResult.NavVO> navs = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVO nav = new SearchResult.NavVO();
                String[] s = attr.split(this.splitChar);
                nav.setNavValue(s[1]);
                // 放入包含的
                result.getAttrIds().add(Long.parseLong(s[0]));

                R r = productFeignService.getAttrInfo(Long.parseLong(s[0]));

                if (r.getCode() == 0) {
                    AttrResponseVO data = r.getData("attr", new TypeReference<AttrResponseVO>() {
                    });
                    nav.setNavName(data.getAttrName());
                } else {
                    nav.setNavName(s[0]);
                }
                // 取消面包屑会怎样，将请求地址的url置空，
                // 拿取所有查询条件，对应置空
                String replace = replaceQueryString(param.get_queryString(), attr, "attrs");
                nav.setLink(HTTP_SEARCH_LIST + replace);

                return nav;
            }).collect(Collectors.toList());


            result.setNavs(navs);

        }
        // 品牌 分类
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            List<SearchResult.NavVO> navs = result.getNavs();
            SearchResult.NavVO nav = new SearchResult.NavVO();
            nav.setNavName("品牌");
            // TODO 远程查询品牌
            R r = productFeignService.getBrandsInfo(param.getBrandId());
            if (r.getCode() == 0) {
                List<BrandVO> brand = r.getData("brand", new TypeReference<List<BrandVO>>() {
                });
                String replace = param.get_queryString();
                StringBuilder sb = new StringBuilder();
                for (BrandVO brandVO : brand) {
                    log.debug("brandVO:{}", brandVO);
                    sb.append(brandVO.getBrandName()).append(";");
                    if(!StringUtils.isEmpty(replace) && !StringUtils.isEmpty(brandVO.getBrandName())){
                        replace = replaceQueryString(replace, brandVO.getBrandId().toString(), "brandId");
                    }

                }
                nav.setNavValue(sb.toString().intern());
                nav.setLink(HTTP_SEARCH_LIST + replace);
                navs.add(nav);
            }

        }
        // TODO 分类,不需要导航取消


        return result;
    }

    private String replaceQueryString(String param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            // 前端和 Java 差异化处理
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String replace = param.replace("&" + key + "=" + encode, "");
        return replace;
    }

    /**
     * keyword、catalogId、sort、过滤条件、页码信息
     *
     * @return 构建检索请求
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        // 构建 dsl 语句的
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /*
        查询： 模糊匹配 keyword、catalogId、过滤条件
         */
        // 1.0.构建 boolQuery
        BoolQueryBuilder boolQueryBuilder = buildBoolQuery(param);

        // 把以前所有条件拿来进行封装
        sourceBuilder.query(boolQueryBuilder);
        /*
        sort、页码信息
         */
        // 2.1 排序

        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split(this.splitChar);
            SortOrder order = "asc".equalsIgnoreCase(s[1]) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        // 2.2 分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
        // 2.3 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /*
        聚合分析
         */
        // TODO 最困难的聚合分析

        // 3.1 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        // 3.1.1 品牌聚合的子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

        sourceBuilder.aggregation(brandAgg);

        // 3.2 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId").size(20);
        // 3.2.1 分类聚合的子聚合
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

        sourceBuilder.aggregation(catalogAgg);

        // 3.3 属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        // 3.3.1 属性聚合的子聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        // 3.3.1.1 属性聚合的子聚合的子聚合
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);

        sourceBuilder.aggregation(attrAgg);


        log.debug("构建的 DSL ：{}", sourceBuilder);


        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }

    /**
     * 构建 bool语句
     *
     * @param param 构建条件
     * @return boolQuery dsl语句
     */
    private BoolQueryBuilder buildBoolQuery(SearchParam param) {


        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 1.1 must
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));

        }
        // 1.2 filter
        // 1.2.1 分类
        if (param.getCatalogId() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalogId()));
        }
        // 1.2.2 品牌
        if (param.getBrandId() != null) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // TODO  1.2.3  属性
        if (param.getAttrs() != null && !param.getAttrs().isEmpty()) {
            param.getAttrs().forEach(item -> {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();

                String[] s = item.split(this.splitChar);
                String attrId = s[0]; // 检索的属性 id
                String[] attrValues = s[1].split(":"); // 检索的属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                // 关键点，，每一个都得生成一个 nested 查询
                boolQueryBuilder.filter(nestedQuery);
            });

        }
        // 1.2.4 有货？
        if (param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        // 1.2.5 价格区间
        if (!StringUtils.isEmpty(param.getPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

            String[] s = param.getPrice().split(this.splitChar);
            log.debug("s:{}", Arrays.toString(s));
            //noinspection AlibabaUndefineMagicConstant
            if (s.length >= 2) {
                // 区间
                if (StringUtils.isEmpty(s[0])) {
                    rangeQuery.to(s[1]);
                } else if (StringUtils.isEmpty(s[1])) {
                    rangeQuery.from(s[0]);
                } else {
                    rangeQuery.from(s[0]).to(s[1]);
                }
            } else if (s.length == 1) {
                if (param.getPrice().startsWith(this.splitChar)) {
                    rangeQuery.to(s[0]);
                }
                if (param.getPrice().endsWith(this.splitChar)) {
                    rangeQuery.from(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        return boolQueryBuilder;
    }
}
